#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<string>
using namespace std;
#define KEY 6
char *keyword[KEY] = {"for","if","then","else","while","do"};
char id[1024] = {};
int num = 0;
int token = -1;

bool ischar(char c)
{
	if(c >= 97 && c <= 122)
		return true;
	return false;
}
int pipei(char *s)
{
	int i = 0;
	for(i = 0;i < KEY;i++)
	{
		if(strcmp(s,keyword[i]) == 0)
			return i + 1;
	}
	return -1;
}
void lexical(FILE *fp)
{
	int i = 0;
	char x = getc(fp);

	num = 0;
	//strcpy(id,"\0");
	for(i = 0;i <1024;i++)
		id[i] = '\0';
	i = 0;

	switch(x)
	{
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	case 'g':
	case 'h':
	case 'i':
	case 'j':
	case 'k':
	case 'l':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 'q':
	case 'r':
	case 's':
	case 't':
	case 'u':
	case 'v':
	case 'w':
	case 'x':
	case 'y':
	case 'z':{
				while(ischar(x)||isdigit(x))
				{
					id[i++] = x;
					x = getc(fp);
					
				}
				ungetc(x,fp);
				token = pipei(id);
				token = (token == -1) ? 10 : token;
			 }break;
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':{
				while(isdigit(x))
				{
					//strcat(id,&x);
					id[i++] = x;
					x = getc(fp);
					
				}
				num = atoi(id);
				ungetc(x,fp);
				token = 11;
			 }break;
	case '+':{
				id[i++] = x;
				token = 13;
			 }break;
	case '-':{
				id[i++] = x;
				token = 14;
			 }break;
	case '*':{
				id[i++] = x;
				token = 15;
			 }break;
	case '/':{
				id[i++] = x;
				token = 16;
			 }break;
	case ':':{
				id[i++] = x;
				token = 17;
				x = getc(fp);
				if(x == '=')
				{
					id[i++] = x;
					token = 18;
			
				}
				else
					ungetc(x,fp);
			 }break;
	case '<':{
				id[i++] = x;
				token = 20;
				x = getc(fp);
				if(x == '>')
				{
					id[i++] = x;
					token = 21;
			
				}
				else if(x == '=')
				{
					id[i++] = x;
					token = 22;
			
				}
				else
					ungetc(x,fp);
			 }break;
	case '>':{
				id[i++] = x;
				token = 23;
				x = getc(fp);
				if(x == '=')
				{
					id[i++] = x;
					token = 24;
			
				}
				else
					ungetc(x,fp);
			 }break;
	case '=':{
				id[i++] = x;
				token = 25;
			 }break;
	case ';':{
				id[i++] = x;
				token = 26;
			 }break;
	case '(':{
				id[i++] = x;
				token = 27;
			 }break;
	case ')':{
				id[i++] = x;
				token = 28;
			 }break;
	case '#':{
				id[i++] = x;
				token = 0;
			 }break;
	default:token = -2;break;
	}
}

int main(int argc,const char *argv[])
{
	if(argc < 2)
	{
		printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1],"r");
	do
	{
		lexical(fp);
		switch(token)
		{
		case 10:
			printf("(id,%s)\n",id);
			break;
		case 11:
			printf("(num,%d)\n",num);
			break;
		case -1:
			printf("error!\n");
			break;
		case -2:
			break;
		default:
			printf("(%d,%s)\n",token,id);
		}
	}while(token != 0);

	fclose(fp);
	return 0;
}
